# x的平方根： https://leetcode-cn.com/problems/sqrtx/

# 我自己的思路
class Solution:
    def mySqrt(self, x: int) -> int:
        """
            二分查找
        """
        left = 0; right = x
        while left <= right:
            mid = left + (right - left) // 2

            # 1. 如果恰好是，则返回
            if mid **2 == x:
                return mid
            # 2. 如果大于 x
            elif mid**2 > x:
                # 如果 mid - 1 小于，返回mid - 1
                if (mid - 1) **2 < x:
                    return mid - 1
                # 否则right = mid - 1
                else:
                    right = mid - 1
            elif mid**2 < x:
                if (mid + 1)**2 > x:
                    return mid
                else:
                    left = mid + 1
        return 0


# 官方题解
class Solution:
    def mySqrt(self, x: int) -> int:
        l, r, ans = 0, x, -1
        while l <= r:
            mid = (l + r) // 2
            if mid * mid <= x:
                ans = mid
                l = mid + 1
            else:
                r = mid - 1
        return ans
